import qs from 'qs';
import { Toast } from 'antd-mobile';
import moment from 'moment';
import { message } from 'antd';
import { getToken, getEditor, replaceUrlParams } from '@inbiz/utils';
import { getProcessInfo } from './web/service';
import { getMessage } from '@inbiz/react';
import { goProcessDetail, goProcessDrawerDetail } from './web/utils';

export const formatProcessName = (activeTab: string, item: any) => {
  switch (activeTab) {
    case '2':
    case '5':
    case '7':
    case '8':
      //XXX发起的【XXX】流程
      return getMessage(`processCenter.easyH51`, {
        0: item?.initiatorName || item?.starterName,
        1: item?.processName,
      });

    case '3':
    case '6':
      //我发起的【XXX】流程
      return getMessage(`processCenter.easyH52`, { 0: item?.processName });

    case '4':
      //我保存的【XXX】流程草稿
      return getMessage(`processCenter.easyH53`, { 0: item?.processName });

    case '9':
      //我将XXX的【XXX】指派给了XXX
      return getMessage(`processCenter.easyH54`, {
        0: item?.initiatorName,
        1: item?.processName,
        2: item?.Assignment,
      });

    case '10':
      //【XXX】将指派给XXX
      return getMessage(`processCenter.easyH55`, { 0: item?.processName, 1: item?.attorneyName });

    case '11':
      return item?.processName + '-' + item?.stepName;
  }
};

export const formatTime = (time: string) => {
  if (moment(time).isSame(moment(), 'day')) {
    //今天
    return moment(time).format('HH:mm');
  } else if (moment(time).isSame(moment(), 'year')) {
    //今年
    return moment(time).format('MM-DD');
  } else {
    //其他
    return moment(time).format('YYYY-MM-DD');
  }
};

export const getSummary = (summary: string) => {
  const firstindex = summary.indexOf('>');
  const lastindex = summary.indexOf('</');
  const theSummary = summary.slice(firstindex + 1, lastindex);
  return theSummary;
};

export const getDetail = (item: any, activeTab: string, callback: Function, setLoading?: Function) => {
  let params =
    activeTab == '4'
      ? {
        processDefinitionId: item.procDefId,
        businessKey: item.businessKey,
        drafID: item.draftsId,
        inItiateApplication: true,
        taskState: item.taskState,
        siteType: 0,
      }
      : activeTab == '1'
        ? {
          processDefinitionId: item.processDefinitionId,
          inItiateApplication: true,
          siteType: 0,
        }
        : {
          taskIds: item.taskId,
          processInstanceId: item.processInstanceId,
          inItiateApplication: false,
          drafID: item.draftsId,
          taskState: item.taskState,
          siteType: 0,
        };
  const { search } = window.location;
  const pName = location.pathname.split('/');
  const pindex = pName.length - 1;
  setLoading && setLoading(true);
  getProcessInfo(params).then((res) => {
    if (res.details && res.details.length > 0 && !res.details[0].formId) {
      if (!res.details[0].url && !res.details[0].outsideUrl) {
        setLoading && setLoading(false);
        return message.error({
          content: getMessage('processCenter.checkPageConfig'),
          key: '1',
        });
      }
      const query = {
        id: res?.details?.[0]?.businessKey || params?.businessKey,
        taskId: res?.details?.[0]?.taskId || params?.taskIds,
        // processId: res.details[0].processDefinitionId,
        instanceId: res.details[0].processInstanceId,
        formId: res.details[0].pageId,
        tabKey: activeTab,
        drafID: params.drafID ?? '',
        draftsId: params.drafID ?? '',
        taskState: res.details[0].taskState ?? params.taskState,
        pageId: res.details[0].pageId,
      };
      pName[pindex] = `${res.details[0]?.siteDomName}`;

      let searchParams = search;
      try {
        searchParams = replaceUrlParams(`dataVersionId=${res.details[0].pageVersion || ''}`, 'search');
      } catch (err) { }
      let _search = searchParams || search;
      const isDev = process.env.NODE_ENV == 'development';
      const detail = res?.details?.[0];
      let newQuery = '';
      if (detail.formTypes == 2) {
        switch (activeTab) {
          case '2':
          case '7':
          case '5':
            newQuery = `&id=${res?.details?.[0]?.businessKey || params?.businessKey}&taskId=${res?.details?.[0]?.taskId || params?.taskIds}&instanceId=${res.details[0].processInstanceId}&taskState=${res.details[0].taskState ?? params.taskState}`;
            break;
          case '3':
          case '6':
          case '8':
            newQuery = `&id=${res?.details?.[0]?.businessKey || params?.businessKey}&instanceId=${res.details[0].processInstanceId}&taskState=${res.details[0].taskState ?? params.taskState}`;
            break;
          case '4':
            newQuery = `&id=${res?.details?.[0]?.businessKey || params?.businessKey}&draftsId=${params.drafID ?? ''}`
            break;
          default:
            break;
        }
      }
      newQuery = newQuery + `&tabKey=${activeTab}`;
      callback &&
        callback(
          detail.formTypes == 2 ? `${location.origin}${isDev ? '/' : '/inbiz/form/'}${detail.pageId}?v=${detail.pageVersion}&platform=web#${isDev ? '/form' : ""}${detail.url}?appid=${detail.appId}&processId=${detail.processDefinitionId}${newQuery}` :
            detail.outsideUrl ? detail.outsideUrl + `?${qs.stringify(query)}&processId=${res.details[0].processDefinitionId}` :
              `${location.origin}${pName.join('/')}${_search}${_search ? '&hideLayout=true' : '?hideLayout=true'
              }#${process.env.NODE_ENV == 'development' ? '/preview/page' : '/page'}${res.details[0].url
              }?${qs.stringify(query)}&processId=${res.details[0].processDefinitionId}`,
          'v6',
        );
    } else if (res.details && res.details.length > 0 && res.details[0].formId) {
      let taskType = '',
        taskId = '',
        incidentId = '';
      switch (activeTab) {
        case '2': // 待办
          taskType = 'InboxTask';
          taskId = res.details[0].taskId ?? '';
          incidentId = res.details[0].processInstanceId ?? '';
          break;
        case '4': // 草稿
          taskType = 'begintask';
          break;
        case '3': // 申请中  我的申请
        case '6':
          taskType = 'mystarttask';
          incidentId = res.details[0].processInstanceId ?? '';
          break;
        case '7': // 已办
          taskType = 'CompleteTask';
          taskId = res.details[0].taskId ?? '';
          incidentId = res.details[0].processInstanceId ?? '';
          break;
        case '5': // 抄送
        case '8': // 归档
          taskType = 'ArchiveTask';
          incidentId = res.details[0].processInstanceId ?? '';
          break;
        default:
          taskType = 'begintask';
          break;
      }
      const querys = {
        taskType,
        taskId,
        id: res?.details?.[0]?.businessKey || params?.businessKey,
        processId: res.details[0].processId,
        formver: res.details[0].formver,
        incidentId,
        formId: res.details[0].formId,
        taskState: params.taskState,
        draftsId: params.drafID ?? '',
      };
      callback && callback(`${location.origin}${res.details[0].url}?${qs.stringify(querys)}`, 'v5');
    } else {
      message.error({
        content: getMessage('processCenter.checkPageConfig'),
        key: 1,
      });
    }
    setLoading && setLoading(false);
  })
};

export const getProcessInfoAfterCustomClickItem = async (params: any) => await getProcessInfo(params);

export const goto = (
  params: {
    processDefinitionId?: any;
    businessKey?: any;
    drafID?: any;
    inItiateApplication?: any;
    taskState?: any;
    siteType?: number;
    processInstanceId?: any;
    starter?: any;
    taskIds?: any;
  },
  tabKey: string,
  type: string,
  e?: React.MouseEvent,
  type2?: string | number | undefined,
  beforeUnloadFunction?: (() => void) | undefined,
  setLoading?: Function,
) => {
  if (getEditor()) {
    return;
  }
  if (e) {
    e.preventDefault();
    e.stopPropagation();
  }
  const location = window.location;
  const { search } = location;
  const pName = location.pathname.split('/');
  const pindex = pName.length - 1;
  localStorage.removeItem('lastUrl');
  localStorage.setItem('lastUrl', window.location.href);
  setLoading && setLoading(true);
  getProcessInfo(params).then((res) => {
    if (res.details && res.details.length > 0 && !res.details[0].formId) {
      if (!res.details[0].url && !res.details[0].outsideUrl && type == 'web') {
        setLoading && setLoading(false);
        return message.error({
          content: getMessage('processCenter.checkPageConfig'),
          key: '1',
        });
      } else if (!res.details[0].url && !res.details[0].outsideUrl && type == 'wap') {
        setLoading && setLoading(false);
        return Toast.show({
          content: getMessage('processCenter.checkPageConfig'),
        });
      } else if (!res || (!res.details && type == 'wap')) {
        setLoading && setLoading(false);
        return Toast.show({
          content: res.message,
        });
      }

      const query = {
        ...location.query,
        id: res?.details?.[0]?.businessKey || params?.businessKey,
        taskId: res?.details?.[0]?.taskId || params?.taskIds,
        // processId: res.details[0].processDefinitionId,
        instanceId: res.details[0].processInstanceId,
        // processInstanceId: res.details[0].processInstanceId,
        // pageVersion: res.details[0].pageVersion,
        // dataVersionId: res.details[0].pageVersion,
        formId: res.details[0].pageId,
        tabKey,
        drafID: params.drafID ?? '',
        draftsId: params.drafID ?? '',
        // starter,
        taskState: res.details[0].taskState ?? params.taskState,
        pageId: res.details[0].pageId,
      };
      pName[pindex] = `${res.details[0]?.siteDomName}`;
      // 解决ios不能执行window.open的问题
      const dom = document.createElement('a');
      // dom.setAttribute(
      //   'href',
      //   `${location.origin}${pName.join('/')}${search}#${res.details[0].url}?${qs.stringify(
      //     query,
      //   )}`,
      // );
      // dom.setAttribute('target', `_blank`);
      // document.body.appendChild(dom);
      // dom.click();
      // dom.remove();

      // 处理一下search参数 ?v=xxxx => v= dataVersionId res.details[0].pageVersion
      let searchParams = search;
      try {
        searchParams = replaceUrlParams(`dataVersionId=${res.details[0].pageVersion || ''}`, 'search');
      } catch (err) { }
      // const childwindow = window.open('', '_blank');
      let _search = searchParams || search;
      const isDev = process.env.NODE_ENV == 'development';
      const detail = res?.details?.[0];
      let newQuery = '';
      if (detail.formTypes == 2) {
        switch (tabKey) {
          case '2':
          case '7':
          case '5':
            newQuery = `&id=${res?.details?.[0]?.businessKey || params?.businessKey}&taskId=${res?.details?.[0]?.taskId || params?.taskIds}&instanceId=${res.details[0].processInstanceId}&taskState=${res.details[0].taskState ?? params.taskState}`;
            break;
          case '3':
          case '6':
          case '8':
            newQuery = `&id=${res?.details?.[0]?.businessKey || params?.businessKey}&instanceId=${res.details[0].processInstanceId}&taskState=${res.details[0].taskState ?? params.taskState}`;
            break;
          case '4':
            newQuery = `&id=${res?.details?.[0]?.businessKey || params?.businessKey}&draftsId=${params.drafID ?? ''}`
            break;
          default:
            break;
        }
      }
      newQuery = newQuery + `&tabKey=${tabKey}`;
      const newUrl = detail.formTypes == 2 ? `${location.origin}${isDev ? '/' : '/inbiz/form/'}${detail?.pageId}?v=${detail.pageVersion}&platform=${type}#${isDev ? '/form' : ''}${detail?.url}?appid=${detail.appId}&processId=${detail?.processDefinitionId}${newQuery}` : detail.outsideUrl ? detail.outsideUrl + `?${qs.stringify(query)}&processId=${res.details[0].processDefinitionId}` : `${location.origin}${pName.join('/')}${_search}${_search ? '&hideLayout=true' : '?hideLayout=true'
        }#${process.env.NODE_ENV == 'development' ? '/preview/page' : '/page'}${res.details[0].url
        }?${qs.stringify(query)}&processId=${res.details[0].processDefinitionId}`;
      if (type == 'web') {
        const childWindow = window.open(newUrl);
        setTimeout(() => {
          childWindow?.addEventListener('beforeunload', () => {
            if (beforeUnloadFunction) {
              beforeUnloadFunction();
            } else {
              if (tabKey != '1') {
                window.location.reload();
              }
            }
          });
        }, 200);
      } else if (type == 'wap') {
        window.location.href = newUrl;
      }
    } else if (res.details && res.details.length > 0 && res.details[0].formId) {
      let taskType = '',
        taskId = '',
        incidentId = '';
      let hash = window.location.hash;
      if (type2) {
        hash = JSON.parse(localStorage.getItem('lastLocation') as string).hash;
      }
      switch (tabKey) {
        case '1':
          taskType = 'begintask';
          break;
        case '2': // 待办
          taskType = 'InboxTask';
          taskId = res.details[0].taskId ?? '';
          incidentId = res.details[0].processInstanceId ?? '';
          break;
        case '4': // 草稿
          taskType = 'begintask';
          break;
        case '3': // 申请中  我的申请
        case '6':
          taskType = 'mystarttask';
          incidentId = res.details[0].processInstanceId ?? '';
          break;
        case '7': // 已办
          taskType = 'CompleteTask';
          taskId = res.details[0].taskId ?? '';
          incidentId = res.details[0].processInstanceId ?? '';
          break;
        case '5': // 抄送
        case '8': // 归档
          taskType = 'ArchiveTask';
          incidentId = res.details[0].processInstanceId ?? '';
          break;
        default:
          taskType = 'archivetask';
          incidentId = res.details[0].processInstanceId ?? '';
          break;
      }
      const querys = {
        taskType,
        taskId,
        id: res?.details?.[0]?.businessKey || params?.businessKey,
        processId: res.details[0].processId,
        formver: res.details[0].formver,
        incidentId,
        formId: res.details[0].formId,
        taskState: params.taskState,
        draftsId: params.drafID ?? '',
      };

      const mobileQuery = {
        taskType,
        taskId,
        businessKey: res?.details?.[0]?.businessKey || params?.businessKey,
        processId: res.details[0].processId,
        formver: res.details[0].formver,
        incidentId,
        formId: res.details[0].formId,
        state: params.taskState ?? '',
        isMobile: true,
        orgToken: getToken(),
        token: getToken(),
        draftsId: params.drafID ?? '',
      };
      if (type == 'web') {
        const childWindow = window.open(
          `${location.origin}${res.details[0].url}?${qs.stringify(querys)}`,
        );
        if (tabKey) {
          setTimeout(() => {
            childWindow?.addEventListener('beforeunload', () => {
              if (beforeUnloadFunction) {
                beforeUnloadFunction();
              } else {
                if (tabKey != '1') {
                  window.location.reload();
                }
              }
            });
          }, 200);
        }
      } else {
        fetch(`/edoc2Flow-web/edoc2-form/jumptoform?${qs.stringify(mobileQuery)}`)
          .then((res) => {
            if (res.ok) {
              return res.text();
            }
          })
          .then((re) => {
            let jumpUrl = '';
            let bakUrl = '';
            let id = '';
            let draftsId = '';
            if (params.drafID) {
              draftsId = `&draftsId=${params.drafID}`;
            }
            if (params?.businessKey) {
              id = `&id=${params.businessKey}`;
            }
            bakUrl = window.location.href;
            jumpUrl =
              re +
              `${id}${draftsId}&jumpType=${encodeURIComponent(bakUrl)}&hash=` +
              encodeURIComponent(hash);
            window.location.replace(jumpUrl)
            // window.location.href = jumpUrl;
          });
      }
    } else {
      if (type == 'web') {
        setLoading && setLoading(false);
        return message.error({
          content: getMessage('processCenter.checkPageConfig'),
          key: 1,
        });
      } else if (type == 'wap') {
        setLoading && setLoading(false);
        return Toast.show({
          content: getMessage('processCenter.checkPageConfig'),
        });
      }
    }
    setLoading && setLoading(false);
  });
};

export const goPopupDetail = (
  item: any,
  activeTab: string,
  openPopUpHeight: any,
  openPopUpWidth: any,
  setLoading?: Function,
  callback?: Function,
) => {
  localStorage.setItem('process-easy-view-approval-success', 'false');
  getDetail(item, activeTab, (url: string, version: string) => {
    goProcessDetail(
      item?.ProcessName || item?.processName,
      url,
      version,
      () => {
        callback && callback();
      },
      openPopUpHeight,
      openPopUpWidth,
    );
  }, setLoading);
};

export const goDrawerDetail = (
  item: any,
  activeTab: string,
  drawerWidth: any,
  setLoading?: Function,
  callback?: Function,
) => {
  localStorage.setItem('process-easy-view-approval-success', 'false');
  getDetail(item, activeTab, (url: string, version: string) => {
    goProcessDrawerDetail(
      item?.ProcessName || item?.processName,
      url,
      version,
      () => {
        callback && callback();
      },
      drawerWidth,
    );
  }, setLoading);
};

/**
 * 加签 #8fc2e9
 * 完成 #71b771
 */
export const processState = {
  '-1': {
    stateName: 'processCenter.wrongState',
    stateIcon: 'icon-process-shenpi',
    stateColor: '#1677ff',
    stateBgColor: '#5a9fff',
    stateFontColor: '#fff',
  },
  '0': {
    stateName: 'processCenter.approvaling',
    stateIcon: 'icon-process-shenpi',
    stateColor: '#1677ff',
    stateBgColor: '#5a9fff',
    stateFontColor: '#fff',
  },
  '1': {
    stateName: 'processCenter.terminate',
    stateIcon: 'icon-process-zhongzhi',
    stateColor: '#e7290f',
    stateBgColor: '#ec705f',
    stateFontColor: '#fff',
  },
  '220': {
    stateName: 'processCenter.launch',
    stateIcon: 'icon-process-faqi',
    stateColor: '#19aacf',
    stateBgColor: '#19AACF',
    stateFontColor: '#fff',
  },

  '5': {
    stateName: 'processCenter.returnsBack',
    stateIcon: 'icon-process-tuihui',
    stateColor: '#ff973b',
    stateBgColor: '#ee973f',
    stateFontColor: '#fff',
  },
  '10': {
    stateName: 'processCenter.beenreturnsBack',
    stateIcon: 'icon-process-tuihui',
    stateColor: 'rgb(238, 151, 63)',
    stateBgColor: '#ee973f',
    stateFontColor: '#fff',
  },
  '20': {
    stateName: 'processCenter.complete',
    stateIcon: 'icon-process-wancheng',
    stateColor: '#71b771',
    stateBgColor: '#71b771',
    stateFontColor: '#fff',
  },
  '50': {
    stateName: 'processCenter.assign',
    stateIcon: 'icon-process-zhipai',
    stateColor: '#a3acb9',
    stateBgColor: '#a3acb9',
    stateFontColor: '#fff',
  },
  '100': {
    stateName: 'processCenter.complete',
    stateIcon: 'icon-process-wancheng',
    stateColor: '#71b771',
    stateBgColor: '#71b771',
    stateFontColor: '#fff',
  },
  '120': {
    stateName: 'processCenter.revoke',
    stateIcon: 'icon-process-zhongzhi',
    stateColor: 'rgb(236, 112, 95)',
    stateBgColor: '#ec705f',
    stateFontColor: '#fff',
  },
  '130': {
    stateName: 'processCenter.plussign',
    stateIcon: 'icon-process-zhongzhi',
    stateColor: 'rgb(236, 112, 95)',
    stateBgColor: '#8fc2e9',
    stateFontColor: '#fff',
  },
  '140': {
    stateName: 'processCenter.complete',
    stateIcon: 'icon-process-wancheng',
    stateColor: '#71b771',
    stateBgColor: '#71b771',
    stateFontColor: '#fff',
  },
  '150': {
    stateName: 'processCenter.complete',
    stateIcon: 'icon-process-wancheng',
    stateColor: '#71b771',
    stateBgColor: '#71b771',
    stateFontColor: '#fff',
  },
  '160': {
    stateName: 'processCenter.complete',
    stateIcon: 'icon-process-wancheng',
    stateColor: '#71b771',
    stateBgColor: '#71b771',
    stateFontColor: '#fff',
  },
  '170': {
    stateName: 'processCenter.terminate',
    stateIcon: 'icon-process-zhongzhi',
    stateColor: '#e7290f',
    stateBgColor: '#ec705f',
    stateFontColor: '#fff',
  },
  '180': {
    stateName: 'processCenter.refuse',
    stateIcon: 'icon-process-zhongzhi',
    stateColor: '#e7290f',
    stateBgColor: '#ec705f',
    stateFontColor: '#fff',
  },
};
